const express = require("express");
const db = require("../config");
const addressRouter = express.Router();

/* 获取指定用户的地址 */
addressRouter.get("/getAddress", (req, res) => {
    const sql = "select * from db_adress where userId=?";
    
    db.query(sql,req.query.userId, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("获取地址失败");
        res.send({
            status: 0,
            message: "获取地址成功",
            data:result
        })
    });

});
/* 更新指定用户的指定地址 */
addressRouter.post("/updateAddress", (req, res) => {
    const { id, name, phone, address, is_default, } = req.body;
    const sql = "update db_adress set receiver_name=?, receiver_phone=?, address=?, is_default=? where id=?";
    db.query(sql, [name, phone, address, is_default, id], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("更新地址失败");
        res.send({
            status: 0,
            message: "更新地址成功"
        })
    });

});
/* 删除指定用户的指定地址 */
addressRouter.post("/delAddress", (req, res) => {
    const sql = "delete from db_adress where id=?";
    db.query(sql, req.body.id, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("删除地址失败");
        res.send({
            status: 0,
            message: "删除地址成功"
        })
    });

});
/* 增加指定用户的地址 */
addressRouter.post("/addAddress", (req, res) => {
    const { userId, name, phone, address, is_default } = req.body;
    const sql = "insert into db_adress(userId,receiver_name,receiver_phone,address,is_default) values(?,?,?,?,?)";
    db.query(sql, [userId, name, phone, address, is_default], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("添加地址失败");
        res.send({
            status: 0,
            message: "添加地址成功"
        })
    });


});
/* 获取所有的地址 */
addressRouter.get("/getAllAddress", (req, res) => {
    const sql = "select * from db_adress";
    
    db.query(sql,req.query.userId, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("获取全部地址失败");
        res.send({
            status: 0,
            message: "获取全部地址成功",
            data:result
        })
    });

});
module.exports = { addressRouter };